package com.vessel.decoration.mvp.ui.fragment.main;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.http.imageloader.glide.ImageConfigImpl;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.utils.DeviceUtils;
import com.jess.arms.utils.PermissionUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.vessel.decoration.BuildConfig;
import com.vessel.decoration.R;
import com.vessel.decoration.app.base.MySupportFragment;
import com.vessel.decoration.app.constant.Constants;
import com.vessel.decoration.app.constant.SPConstant;
import com.vessel.decoration.app.data.api.service.CommonService;
import com.vessel.decoration.app.data.entity.UserInfoResponse;
import com.vessel.decoration.app.utils.HttpResultFunc;
import com.vessel.decoration.app.utils.UiHelper;
import com.vessel.decoration.mvp.ui.widget.RoundImage;

import org.simple.eventbus.Subscriber;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @author vesselzhang
 * @date 2017/11/28
 */

public class MeTabFragment extends MySupportFragment {

    @BindView(R.id.me_login_layout)
    View login;
    @BindView(R.id.me_logout_layout)
    View logout;
    @BindView(R.id.me_userinfo_avatar)
    RoundImage avatar;
    @BindView(R.id.me_userinfo_name)
    TextView name;

    @BindView(R.id.me_order)
    View orderView;
    @BindView(R.id.me_collect)
    View collectView;
    @BindView(R.id.me_address)
    View addressView;
    @BindView(R.id.me_notepad)
    View notepadView;


    //manage
    @BindView(R.id.me_manage_layout)
    View manageLayout;
    @BindView(R.id.me_manage_divider)
    View dividerLayout;
    @BindView(R.id.me_business)
    View businessView;
    @BindView(R.id.me_worker)
    View workerView;


    @BindView(R.id.me_share)
    View shareView;
    @BindView(R.id.me_suggest)
    View suggestView;
    @BindView(R.id.me_about)
    View aboutView;
    @BindView(R.id.me_contact)
    View contactView;

    @BindString(R.string.me_item_order)
    String mOrderStr;
    @BindString(R.string.me_item_collect)
    String mCollectStr;
    @BindString(R.string.me_item_address)
    String mAddressStr;
    @BindString(R.string.me_item_notepad)
    String mNotepadStr;
    @BindString(R.string.me_item_business)
    String mBusinessStr;
    @BindString(R.string.me_item_worker)
    String mWorkerStr;
    @BindString(R.string.me_item_share)
    String mShareStr;
    @BindString(R.string.me_item_suggest)
    String mSuggestStr;
    @BindString(R.string.me_item_about)
    String mAboutStr;
    @BindString(R.string.me_item_contact)
    String mContactStr;

    private String token;
    private AppComponent mAppComponent;
    private IRepositoryManager mRepositoryManager;

    public static MeTabFragment newInstance() {
        return new MeTabFragment();
    }

    @Override
    public void setupFragmentComponent(AppComponent appComponent) {
    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_tab_me, container, false);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mRepositoryManager = ArmsUtils.obtainAppComponentFromContext(getActivity()).repositoryManager();
        mAppComponent = ArmsUtils.obtainAppComponentFromContext(getActivity());
        if (TextUtils.isEmpty(token)) {
            token = DataHelper.getStringSF(getActivity(), SPConstant.SP_TOKEN);
        }

        manage(orderView, R.drawable.icon_order, mOrderStr, v -> { //订单
            if (TextUtils.isEmpty(token)) {
                ARouter.getInstance().build("/app/login").navigation();
                return;
            }
            ARouter.getInstance().build("/app/me")
                    .withSerializable(Constants.PAGE, Constants.PAGE_ORDER)
                    .navigation();
        });
        manage(collectView, R.drawable.icon_collect, mCollectStr, v -> { //收藏
            if (TextUtils.isEmpty(token)) {
                ARouter.getInstance().build("/app/login").navigation();
                return;
            }
            ARouter.getInstance().build("/app/me")
                    .withSerializable(Constants.PAGE, Constants.PAGE_COLLECT)
                    .navigation();
        });
        manage(addressView, R.drawable.icon_address, mAddressStr, v -> { //地址
            if (TextUtils.isEmpty(token)) {
                ARouter.getInstance().build("/app/login").navigation();
                return;
            }
            ARouter.getInstance().build("/app/me")
                    .withSerializable(Constants.PAGE, Constants.PAGE_ADDRESS)
                    .navigation();
        });
        manage(notepadView, R.drawable.icon_notepad, mNotepadStr, v -> { //记事本
            if (TextUtils.isEmpty(token)) {
                ARouter.getInstance().build("/app/login").navigation();
                return;
            }
            ARouter.getInstance().build("/app/me")
                    .withSerializable(Constants.PAGE, Constants.PAGE_NOTEBOOK)
                    .navigation();
        });
        manage(businessView, R.drawable.icon_notepad, mBusinessStr, v -> { //商家
            if (TextUtils.isEmpty(token)) {
                ARouter.getInstance().build("/app/login").navigation();
                return;
            }
            ARouter.getInstance().build("/app/me")
                    .withSerializable(Constants.PAGE, Constants.PAGE_BUSINESS)
                    .navigation();
        });
        manage(workerView, R.drawable.icon_notepad, mWorkerStr, v -> { //技工
            if (TextUtils.isEmpty(token)) {
                ARouter.getInstance().build("/app/login").navigation();
                return;
            }
            ARouter.getInstance().build("/app/me")
                    .withSerializable(Constants.PAGE, Constants.PAGE_WORKER)
                    .navigation();
        });
        manage(shareView, R.drawable.icon_share, mShareStr, null); //分享
        manage(suggestView, R.drawable.icon_notepad, mSuggestStr, v -> { //建议
            ARouter.getInstance().build("/app/me")
                    .withSerializable(Constants.PAGE, Constants.PAGE_SUGGEST)
                    .navigation();
        });
        manage(aboutView, R.drawable.icon_about, mAboutStr, v -> { //关于
            ARouter.getInstance().build("/app/me")
                    .withSerializable(Constants.PAGE, Constants.PAGE_ABOUT)
                    .navigation();
        });
        manage(contactView, R.drawable.icon_contact, mContactStr, v -> { //联系我们
            PermissionUtil.callPhone(new PermissionUtil.RequestPermission() {
                @Override
                public void onRequestPermissionSuccess() {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "13182716780"));
                    startActivity(intent);
                }

                @Override
                public void onRequestPermissionFailure() {
                    ArmsUtils.makeText(getActivity(), "权限被拒绝");
                }
            }, new RxPermissions(getActivity()), mAppComponent.rxErrorHandler());
        });
    }

    @Override
    public void setData(Object data) {

    }

    @Override
    public void onResume() {
        super.onResume();
        token = DataHelper.getStringSF(getActivity(), SPConstant.SP_TOKEN);
        if (TextUtils.isEmpty(token)) {
            login.setVisibility(View.GONE);
            logout.setVisibility(View.VISIBLE);
            orderView.setVisibility(View.GONE);
            Glide.with(getActivity())
                    .load(BuildConfig.APP_DOMAIN)
                    .into(avatar);
            name.setText("");
            setManagePanel(false, false);
            return;
        } else {
            login.setVisibility(View.VISIBLE);
            logout.setVisibility(View.GONE);
            orderView.setVisibility(View.VISIBLE);
            UserInfoResponse userInfo = DataHelper.getDeviceData(getActivity(), SPConstant.SP_USERINFO);
            if (userInfo != null) {
                mAppComponent.imageLoader()
                        .loadImage(getActivity(), ImageConfigImpl
                                .builder()
                                .imageView(avatar)
                                .url(BuildConfig.APP_DOMAIN + userInfo.getIcon())
                                .build());
                name.setText(userInfo.getNickname());
                if (DeviceUtils.getNetworkType(getContext()) != 0) {
                    setManagePanel(userInfo.getIsMerchant() == 1, userInfo.getIsArtisan() == 1);
                }
            }
            //再次获取UserInfo
            mRepositoryManager.obtainRetrofitService(CommonService.class)
                    .queryInfo()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .map(new HttpResultFunc<>())
                    .subscribe(new Observer<UserInfoResponse>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(UserInfoResponse userInfoResponse) {
                            DataHelper.saveDeviceData(getActivity(), SPConstant.SP_USERINFO, userInfoResponse);
                            mAppComponent.imageLoader()
                                    .loadImage(getActivity(), ImageConfigImpl
                                            .builder()
                                            .imageView(avatar)
                                            .url(BuildConfig.APP_DOMAIN + userInfoResponse.getIcon())
                                            .build());

                            name.setText(userInfoResponse.getNickname());
                            setManagePanel(userInfoResponse.getIsMerchant() == 1, userInfoResponse.getIsArtisan() == 1);
                        }

                        @Override
                        public void onError(Throwable e) {
                            setManagePanel(false, false);
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }

    @OnClick({R.id.me_logout_layout, R.id.me_login_layout})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.me_login_layout:
                ARouter.getInstance().build("/app/me")
                        .withSerializable(Constants.PAGE, Constants.PAGE_USERINFO)
                        .navigation();
                break;
            case R.id.me_logout_layout:
                ARouter.getInstance().build("/app/login").navigation();
                break;
        }
    }

    @Subscriber
    public void updateUserInfo(UserInfoResponse userInfoResponse) {
        if (userInfoResponse != null) {
            mAppComponent.imageLoader()
                    .loadImage(getActivity(), ImageConfigImpl
                            .builder()
                            .imageView(avatar)
                            .url(BuildConfig.APP_DOMAIN + userInfoResponse.getIcon())
                            .build());
            name.setText(userInfoResponse.getNickname());
        }
    }

    private void setManagePanel(boolean isMerchant, boolean isArtisan) {
        if (isMerchant && isArtisan) {
            manageLayout.setVisibility(View.VISIBLE);
            dividerLayout.setVisibility(View.VISIBLE);
            businessView.setVisibility(View.VISIBLE);
            workerView.setVisibility(View.VISIBLE);
        } else if (isMerchant && !isArtisan) {
            manageLayout.setVisibility(View.VISIBLE);
            dividerLayout.setVisibility(View.VISIBLE);
            businessView.setVisibility(View.VISIBLE);
            workerView.setVisibility(View.GONE);
        } else if (!isMerchant && isArtisan) {
            manageLayout.setVisibility(View.VISIBLE);
            dividerLayout.setVisibility(View.VISIBLE);
            businessView.setVisibility(View.GONE);
            workerView.setVisibility(View.VISIBLE);
        } else {
            manageLayout.setVisibility(View.GONE);
        }
    }

    private void manage(View itemView, int res, String title, View.OnClickListener listener) {
        ImageView icon = UiHelper.find(itemView, R.id.tv_me_icon);
        icon.setImageResource(res);
        TextView titleTV = UiHelper.find(itemView, R.id.tv_me_title);
        itemView.setOnClickListener(listener);
        titleTV.setText(title);
    }
}
